package com.hmdp.utils;


import cn.hutool.core.lang.UUID;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.concurrent.TimeUnit;

/*
 * 初级锁
 * */
public class SimpleRedis implements Ilocak {

    private String name;//锁的名字
    private StringRedisTemplate stringRedisTemplate;

    public SimpleRedis(String name, StringRedisTemplate stringRedisTemplate) {
        this.name = name;
        this.stringRedisTemplate = stringRedisTemplate;
    }

    private static final String key_prefix = "lock:";
    //用uuid来做线程的前缀为了避免集群环境下多jvm的环境下线程id的冲突
    private static final String id_prefix = UUID.randomUUID().toString(true) + "-";
    //lua脚本,泛型是返回值类型
    private static final DefaultRedisScript<Long> UNLOCK_SCRIPT ;
    //初始化脚本
    static{
        UNLOCK_SCRIPT = new DefaultRedisScript<>();
        UNLOCK_SCRIPT.setLocation( new ClassPathResource("unlock.lua"));
        UNLOCK_SCRIPT.setResultType(Long.class);
    }


    @Override
    public boolean tryLock(Long timeOutSec) {
        //获取线程标识
        String id = id_prefix + Thread.currentThread().getId();
        //获取锁
        Boolean success = stringRedisTemplate.opsForValue().setIfAbsent(key_prefix + name, id, timeOutSec, TimeUnit.SECONDS);

        return Boolean.TRUE.equals(success);//避免空指针风险
    }

  /*  @Override
    public void unLock() {
        //获取线程标识
        String id = id_prefix + Thread.currentThread().getId();
        //判断标识是否一致
        if(id.equals(stringRedisTemplate.opsForValue().get(key_prefix + name))){
            //一至
            //释放锁
            stringRedisTemplate.delete(key_prefix + name);
        }
    }*/



    /*
    * 基于lua脚本释放锁
    * */
    @Override
    public void unLock() {
        //!!!!!!!!!!!!判断和删除是在脚本中执行的原子性可以满足
        //调用lua脚本
        stringRedisTemplate.execute(
                UNLOCK_SCRIPT,
                Collections.singletonList(key_prefix + name),//锁的key
                id_prefix + Thread.currentThread().getId()//当前线程的标识
        );

    }
}
